package com.yuanfeng.gateway.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class CorsResponseHeaderFilter implements GlobalFilter, Ordered {
    private static final Logger logger = LoggerFactory.getLogger(CorsResponseHeaderFilter.class);
    private static final String ANY = "*";

    public CorsResponseHeaderFilter() {
    }

    public int getOrder() {
        return 0;
    }

    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            exchange.getResponse().getHeaders().entrySet().stream().filter((kv) -> {
                return kv.getValue() != null && ((List)kv.getValue()).size() > 1;
            }).filter((kv) -> {
                return ((String)kv.getKey()).equals("Access-Control-Allow-Origin") || ((String)kv.getKey()).equals("Access-Control-Allow-Credentials") || ((String)kv.getKey()).equals("Vary");
            }).forEach((kv) -> {
                if (((String)kv.getKey()).equals("Vary")) {
                    kv.setValue((kv.getValue()).stream().distinct().collect(Collectors.toList()));
                } else {
                    List<String> value = new ArrayList();
                    if (((List)kv.getValue()).contains("*")) {
                        value.add("*");
                        kv.setValue(value);
                    } else {
                        value.add((kv.getValue()).get(0));
                        kv.setValue(value);
                    }
                }
            });
        }));
    }
}
